package edu.zjut.hjg.saas.web.controller.admin;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.zjut.hjg.saas.biz.service.KindergartenService;
import edu.zjut.hjg.saas.biz.service.exception.ServiceException;
import edu.zjut.hjg.saas.biz.support.AppStatus;

@Controller
@RequestMapping("/admin/app")
public class AppManangeController {

    private static final Log    log       = LogFactory.getLog(AppManangeController.class);

    private static final int    PAGE_SIZE = 15;

    @Autowired
    private KindergartenService kindergartenService;

    @RequestMapping("/index.htm")
    public void index(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                      Model model) {
        if (page < 1) {
            page = 1;
        }
        model.addAttribute("paginated", kindergartenService.listByStatus(AppStatus.UNAUDITED,
                PAGE_SIZE, page));
    }

    @RequestMapping("/byStatus.htm")
    public void byStatus(
                         @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                         @RequestParam(value = "status", required = false, defaultValue = "AUDITED") AppStatus status,
                         Model model) {
        if (page < 1) {
            page = 1;
        }
        model.addAttribute("paginated", kindergartenService.listByStatus(status, PAGE_SIZE, page));
        model.addAttribute("appStatus", status.toString());
    }

    @RequestMapping("/ajax/pass.htm")
    @ResponseBody
    public Map<String, Object> pass(@RequestParam("id") int appId) {
        return changeStatus(appId, AppStatus.AUDITED);
    }

    @RequestMapping("/ajax/reject.htm")
    @ResponseBody
    public Map<String, Object> reject(@RequestParam("id") int appId) {
        return changeStatus(appId, AppStatus.REJECTED);
    }

    private Map<String, Object> changeStatus(int id, AppStatus status) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            kindergartenService.updateStatus(id, status);
        } catch (ServiceException e) {
            log.error(e.getMessage() + ", " + e.getErrorMessage(), e);
            map.put("success", false);
            map.put("message", e.getErrorMessage());
        }
        map.put("success", true);
        map.put("status", status.getName());
        return map;
    }
}
